import React, { useState } from 'react';
import {
    Box,
    Paper,
    IconButton,
    Tooltip,
    Popper,
    Grow,
    ClickAwayListener,
    MenuList,
    MenuItem
} from '@mui/material';
import {
    AutoAwesome as PolishIcon,
    KeyboardDoubleArrowRight as SendIcon,
    ContentCopy as CopyIcon,
    FormatAlignJustify as FormatIcon,
    Autorenew,
    FormatClear,
    Assignment,
    Description,
    Layers,
    Brush
} from '@mui/icons-material';
import { SelectedTextInfo, PolishType } from '../../types/text.ts';

// 定义润色选项
const polishOptions: Array<{ type: PolishType, label: string, icon: React.ReactNode }> = [
    { type: 'rewrite', label: '重写', icon: <Autorenew fontSize="small" /> },
    { type: 'simplify', label: '简洁', icon: <FormatClear fontSize="small" /> },
    { type: 'expand', label: '扩展', icon: <Assignment fontSize="small" /> },
    { type: 'summarize', label: '总结', icon: <Description fontSize="small" /> },
    { type: 'enhance', label: '提升', icon: <Layers fontSize="small" /> },
    { type: 'polish', label: '润色', icon: <Brush fontSize="small" /> },
];

// 默认润色类型
const DEFAULT_POLISH_TYPE: PolishType = 'enhance';

interface SelectionToolbarProps {
    anchorEl: HTMLElement | null;
    open: boolean;
    selectionInfo: SelectedTextInfo | null;
    onClose: () => void;
    onSendToAI: (info: SelectedTextInfo) => void;
    onPolishTypeSelect: (type: PolishType, info: SelectedTextInfo) => void;
    onFormatText: (format: string) => void;
}

/**
 * 选中文本悬浮工具栏组件
 */
const SelectionToolbar: React.FC<SelectionToolbarProps> = ({
    anchorEl,
    open,
    selectionInfo,
    onClose,
    onSendToAI,
    onPolishTypeSelect,
    onFormatText
}) => {
    // 格式化菜单状态
    const [formatMenuOpen, setFormatMenuOpen] = useState(false);
    const [polishMenuOpen, setPolishMenuOpen] = useState(false);

    // 将文本发送到AI面板
    const handleSendToAI = () => {
        if (selectionInfo) {
            onSendToAI(selectionInfo);
            onClose();
        }
    };

    // 复制文本
    const handleCopyText = () => {
        if (selectionInfo && selectionInfo.text) {
            navigator.clipboard.writeText(selectionInfo.text);
            onClose();
        }
    };

    // 处理润色选项
    const handleSelectPolishType = (type: PolishType) => {
        if (selectionInfo) {
            onPolishTypeSelect(type, selectionInfo);
            onClose();
        }
    };

    // 直接应用默认润色类型
    const handlePolishIconClick = () => {
        if (selectionInfo) {
            // 应用默认润色类型
            onPolishTypeSelect(DEFAULT_POLISH_TYPE, selectionInfo);
            onClose();
        }
    };

    // 显示润色选项菜单
    const handleShowPolishMenu = (event: React.MouseEvent) => {
        event.stopPropagation(); // 阻止冒泡避免关闭工具栏
        setPolishMenuOpen(true);
        setFormatMenuOpen(false);
    };

    // 打开/关闭格式化菜单
    const handleToggleFormatMenu = () => {
        setFormatMenuOpen(!formatMenuOpen);
        setPolishMenuOpen(false);
    };

    // 处理格式化文本
    const handleFormatText = (format: string) => {
        onFormatText(format);
        setFormatMenuOpen(false);
        onClose();
    };

    if (!open || !anchorEl) return null;

    // 获取默认润色类型的标签
    const defaultPolishLabel = polishOptions.find(o => o.type === DEFAULT_POLISH_TYPE)?.label || '提升';

    return (
        <Popper
            open={open}
            anchorEl={anchorEl}
            placement="top"
            transition
            disablePortal
            style={{ zIndex: 1300 }}
        >
            {({ TransitionProps }) => (
                <Grow
                    {...TransitionProps}
                    style={{ transformOrigin: 'center bottom' }}
                >
                    <Paper elevation={3} sx={{ mt: -1 }}>
                        <ClickAwayListener onClickAway={() => {
                            setFormatMenuOpen(false);
                            setPolishMenuOpen(false);
                            onClose();
                        }}>
                            <Box sx={{ display: 'flex', p: 0.5 }}>
                                <Tooltip title="发送到AI面板">
                                    <IconButton size="small" onClick={handleSendToAI}>
                                        <SendIcon fontSize="small" />
                                    </IconButton>
                                </Tooltip>

                                <Tooltip title={`一键${defaultPolishLabel}(点击)`}>
                                    <Box sx={{ position: 'relative' }}>
                                        <IconButton
                                            size="small"
                                            onClick={handlePolishIconClick}
                                            onContextMenu={(e) => {
                                                e.preventDefault();
                                                handleShowPolishMenu(e);
                                            }}
                                        >
                                            <PolishIcon fontSize="small" />
                                        </IconButton>

                                        {/* 右击显示选项菜单 */}
                                        <Popper
                                            open={polishMenuOpen}
                                            anchorEl={anchorEl}
                                            placement="right-start"
                                            transition
                                            disablePortal
                                            style={{ zIndex: 1301 }}
                                        >
                                            <Paper elevation={3}>
                                                <MenuList dense>
                                                    {polishOptions.map((option) => (
                                                        <MenuItem
                                                            key={option.type}
                                                            onClick={() => handleSelectPolishType(option.type)}
                                                            sx={{ minWidth: '120px' }}
                                                        >
                                                            <Box sx={{ mr: 1, display: 'flex', alignItems: 'center' }}>
                                                                {option.icon}
                                                            </Box>
                                                            {option.label}
                                                        </MenuItem>
                                                    ))}
                                                </MenuList>
                                            </Paper>
                                        </Popper>
                                    </Box>
                                </Tooltip>

                                <Tooltip title="复制">
                                    <IconButton size="small" onClick={handleCopyText}>
                                        <CopyIcon fontSize="small" />
                                    </IconButton>
                                </Tooltip>

                                <Tooltip title="格式化">
                                    <Box>
                                        <IconButton
                                            size="small"
                                            onClick={handleToggleFormatMenu}
                                        >
                                            <FormatIcon fontSize="small" />
                                        </IconButton>

                                        <Popper
                                            open={formatMenuOpen}
                                            anchorEl={anchorEl}
                                            placement="right-start"
                                            transition
                                            disablePortal
                                            style={{ zIndex: 1301 }}
                                        >
                                            <Paper elevation={3}>
                                                <MenuList dense>
                                                    <MenuItem onClick={() => handleFormatText('format-paragraphs')}>
                                                        紧凑段落
                                                    </MenuItem>
                                                </MenuList>
                                            </Paper>
                                        </Popper>
                                    </Box>
                                </Tooltip>
                            </Box>
                        </ClickAwayListener>
                    </Paper>
                </Grow>
            )}
        </Popper>
    );
};

export default SelectionToolbar; 